package com.zlx.sharelive.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.zlx.module_base.base_api.res_data.VideoBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.R;
import com.zlx.sharelive.activity.ShortVideoDetailsAc;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import me.bzcoder.mediapicker.cameralibrary.util.ScreenUtils;

/**
 * 我的点赞 短视频
 */
public class FabulousShortVideoFg extends BaseFg {

    @BindView(R.id.rv_data)
    RecyclerView rv_data;
    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;

    private int page = 1;
    private String state = "1";
    private List<VideoBean.InfoDTO.RecordsDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fg_fabulous_short_video;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initRecyclerView();
        getVideoList(page);

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getVideoList(page);
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mAdapter.notifyItemChanged(msg.arg1);
                    break;
            }
        }
    };


    /**
     * 获取短视频数据
     */
    private void getVideoList(int page) {
        ApiUtil.getHomeApi().getVideoList(SPUtil.getToken(getContext()),
                String.valueOf(page),
                "2", "1", "", "", "", "", "1", "","1").observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<VideoBean> data) {
                sw_layout.setRefreshing(false);
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            if (data.getData().getInfo().size() > 0) {
                                mList.addAll(data.getData().getInfo().get(0).getRecords());
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();

                for (int i = 0; i < mList.size(); i++) {
                    int finalI = i;
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (!StringUt.isEmpty(mList.get(finalI).getVideo())) {
                                if (isValid(mList.get(finalI).getVideo()) == true) {
                                    if (!StringUt.isEmpty(getPlayTime(mList.get(finalI).getVideo()))) {
                                        String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(mList.get(finalI).getVideo())));
                                        mList.get(finalI).setPeriod(time);
                                        Message msg = new Message();
                                        msg.what = 1;
                                        msg.arg1 = finalI;
                                        handler.sendMessage(msg);
                                    }
                                }
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                sw_layout.setRefreshing(false);
            }
        }));
    }


    /**
     * 初始化列表
     */
    private void initRecyclerView() {

        rv_data.setLayoutManager(new GridLayoutManager(getContext(), 2));

        mAdapter = new CommonRecyclerViewAdapter<VideoBean.InfoDTO.RecordsDTO>(getContext(), mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoBean.InfoDTO.RecordsDTO entity, int position) {
                GlideImgManager.glideLoader(getContext(),
                        entity.getAvatar(), holder.getView(R.id.iv_short_video_image), 1);

                Glide.with(getContext())
                        .asBitmap()
                        .load(entity.getCover())
                        .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {

                            @Override
                            public void onResourceReady(@NonNull @NotNull Bitmap bitmap, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                                //这个bitmap就是你图片url加载得到的结果
                                //获取bitmap信息，可赋值给外部变量操作，也可在此时行操作。
                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ((FrameLayout) holder.getView(R.id.fl_layout)).getLayoutParams();//获取你要填充图片的布局的layoutParam
                                layoutParams.height = (int) (((float) bitmap.getHeight()) / bitmap.getWidth() * ScreenUtils.getScreenWidth(getContext()) / 2);
                                //因为是2列,所以宽度是屏幕的一半,高度是根据bitmap的高/宽*屏幕宽的一半
                                layoutParams.width = ScreenUtils.getScreenWidth(getContext()) / 2;//这个是布局的宽度
                                ((FrameLayout) holder.getView(R.id.fl_layout)).setLayoutParams(layoutParams);//容器的宽高设置好了
                                bitmap = zoomImg(bitmap, layoutParams.width, layoutParams.height);
                                // 然后在改变一下bitmap的宽高
                                ((ImageView) holder.getView(R.id.iv_short_video_image)).setImageBitmap(bitmap);
                            }
                        });

                holder.setText(R.id.tv_like_count, entity.getLikeCount());
                if (entity.getIslike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_false);
                }
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_short_video;
            }
        };

        rv_data.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                startActivity(new Intent(getContext(),
                        ShortVideoDetailsAc.class)
                        .putExtra("id", mList.get(position).getId())
                        .putExtra("video", mList.get(position).getVideo())
                );
            }
        });
    }

    private String getPlayTime(String mUri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String duration = "";
        try {
            if (mUri != null) {
                HashMap headers = null;
                if (headers == null) {
                    headers = new HashMap();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }
            //注意地址 mUri= /storage/emulated/0/youshixiu/rectools/录屏专家190629113518.mp4    本地
            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return duration;
    }

    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }

    private boolean isValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }
        return false;
    }

    //改变bitmap尺寸的方法
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

}
